package com.liu.qqRobot.wia.handler;

import cn.hutool.core.codec.Base64;
import com.liu.common.entity.vo.WIAGetFissuresVO;
import com.liu.common.utils.HtmlToImageUtils;
import com.liu.common.utils.QQClientUtils;
import com.liu.common.utils.WIAClientUtils;
import com.liu.mybatisPlus.q.service.QGroupUserOperationQuantityService;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import com.liu.qqRobot.q.enums.OperationTypeEnum;
import freemarker.template.TemplateException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class FissuresHandler {

    @Resource
    private QGroupUserOperationQuantityService qGroupUserOperationQuantityService;

    /**
     * 处理事件
     * @param data 信息内容
     * @param groupId 群号
     * @param userId 发送人QQ号
     * @param fissureType 裂隙类型 1-普通 2-钢铁 3-九重天
     */
    public void handler(EventReportingDTO.Message.Data data, Long groupId, Long userId, Boolean isGroup, Integer fissureType) {
        List<WIAGetFissuresVO> wiaGetFissuresVOList = new ArrayList<>();
        try {
            wiaGetFissuresVOList = WIAClientUtils.getFissures();
        } catch (IOException | ClassNotFoundException | InvocationTargetException | IllegalAccessException |
                 NoSuchMethodException e) {
            log.error("获取warfrmae裂隙信息失败:{}", e.getMessage(), e);
            return;
        }
        switch (fissureType) {
            case 1 -> // 过滤出普通裂隙
                    wiaGetFissuresVOList = wiaGetFissuresVOList.stream()
                            .filter(w -> !w.getIsHard() && !w.getIsStorm() && w.getActive())
                            .collect(Collectors.toList());
            case 2 -> // 过滤出钢铁裂隙
                    wiaGetFissuresVOList = wiaGetFissuresVOList.stream()
                            .filter(w -> w.getIsHard() && !w.getIsStorm() && w.getActive())
                            .collect(Collectors.toList());
            case 3 -> // 过滤出九重天裂隙
                    wiaGetFissuresVOList = wiaGetFissuresVOList.stream()
                            .filter(w -> !w.getIsHard() && w.getIsStorm() && w.getActive())
                            .collect(Collectors.toList());
        }

        Map<String, List<WIAGetFissuresVO>> groupByTier = wiaGetFissuresVOList.stream().collect(Collectors.groupingBy(WIAGetFissuresVO::getTier));
        Map<String, Object> templateParam = new HashMap<>();
        List<Object> tierList = new ArrayList<>();
        for (Map.Entry<String, List<WIAGetFissuresVO>> entry : groupByTier.entrySet()) {
            List<WIAGetFissuresVO> wiaGetFissuresVOS = entry.getValue();
            String tier = entry.getKey();
            Map<String, Object> tierListParam = new HashMap<>();
            tierListParam.put("tier", tier);
            tierListParam.put("wiaGetFissuresVOS", wiaGetFissuresVOS);
            tierList.add(tierListParam);
        }
        templateParam.put("tierList", tierList);
        try {
            HtmlToImageUtils.htmlToImage("warframeFissuresTemplate.html", templateParam,
                    "src/main/resources/picture/warframeFissures.png", 1750);
        } catch (IOException | ParserConfigurationException | TemplateException | SAXException e) {
            log.error("获取warfrmae裂隙模板失败:{}", e.getMessage(), e);
            return;
        }
        File file = new File("src/main/resources/picture/warframeFissures.png");
        String encode = Base64.encode(file);
        String msg = "[CQ:at,qq=" + userId + "]\n[CQ:image,file=base64://" + encode+ ",type=show,subType=0]";
        QQClientUtils.sendMsg(msg, userId, groupId, isGroup);
        qGroupUserOperationQuantityService.statisticsOperationQuantityByType(groupId, userId, OperationTypeEnum.WARFRAME_GET_FISSURE);
    }

}
